<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class PHPEmail
{
	private $_subject, $_message, $_to, $_cc, $sender;
	private $_attachments = array();
	private $CI;

	public function __construct ()
	{
		$this->CI = & get_instance();
		$this->_cc = array();
	}

	public function to ($to)
	{
		$this->_to = (string) $to;
		return $this;
	}

	public function cc ($cc)
	{
		$this->_cc[] = (string) $cc;
		return $this;
	}

	public function subject ($subject)
	{
		$this->_subject = $subject;
		return $this;
	}

	public function message ($message)
	{
		$this->_message = (string) $message;
		return $this;
	}

	public function attachment ($filepath)
	{
		$this->_attachments[] = $filepath;
		return $this;
	}

	public function sender($name)
	{
		$this->_sender = (string) $name;
		return $this;
	}

	/* 
	 * 发送邮件
	 *
	 * @param	string	$message : 邮件正文 (utf-8)编码
	 * @return	boolean
	 */
	public function send ($message = NULL)
	{
		if (! empty($message))
			$this->_message = (string) $message;

		return $this->do_send();
	}

	protected function mail_from ()
	{
		//$suffix  = 'noreply';
		//$prefix  = 'sohuaijia';
		//$rand    = uniqid();
		//$address = "{$prefix}-{$rand}-{$suffix}@appchina.com";
		//$address = 'no-reply@appchina.com';
		$address = 'service@mail.wayatrip.com';

		return $address;
	}

	protected function do_send ()
	{
		$this->CI->load->library('PHPmailer',array(true));
		$this->CI->phpmailer->IsSMTP(); 
		$this->CI->config->load('myemail');
		$smtp=$this->CI->config->item('myemail');

		try {


		$this->CI->phpmailer->Host       = $smtp['smtp_host']; // SMTP server
		$this->CI->phpmailer->CharSet    = $smtp['charset'];
		$this->CI->phpmailer->SMTPDebug  = 0;
		$this->CI->phpmailer->Port       = $smtp['smtp_port'];
		if (empty($this->_sender))
		{
		    $this->_sender = $smtp['email_sender'];
		}
		if (!empty($smtp['auth']))
		{
		    $this->CI->phpmailer->SMTPAuth = true;
		    $this->CI->phpmailer->Username = $smtp['smtp_user'];
		    $this->CI->phpmailer->Password = $smtp['smtp_pass'];
		    $this->CI->phpmailer->SetFrom($smtp['smtp_user'], $this->_sender);
		}
		else 
		{
		    $this->CI->phpmailer->SMTPAuth = false;
		    $this->CI->phpmailer->SetFrom($this->mail_from(), $this->_sender);
		}
		$this->CI->phpmailer->AddAddress($this->_to);
		if (! empty($this->_cc))
		{
			foreach ($this->_cc as $addr)
				$this->CI->phpmailer->AddCC($addr);
		}
		$this->CI->phpmailer->Subject    = $this->_subject;
		$this->CI->phpmailer->isHTML(TRUE);
		$this->CI->phpmailer->Body       = $this->_message;

		if (!empty($this->_attachments))
		{
			foreach ($this->_attachments as $fp)
				$this->CI->phpmailer->AddAttachment($fp);
		}

		$this->CI->phpmailer->Send();

		} 
		catch (Exception $e) 
		{
			return FALSE;
		}

		return TRUE;
	}
}
